<?php
class Ext_Controller_SecureAction extends Ext_Controller_Action
{
    // stores the user object of the currently logged user
    protected $_user;

    protected $_requiresAuth = true;

    protected $_requiresSecurity = true;


    public function preDispatch()
    {
    	//Zend_Debug::dump( $this->_user );exit;
        $insecure = $this->getFrontController()->getParam("insecure");
        if ( $insecure ) {
            return;
        }
        if ( $this->_requiresAuth ) {
            $failedUrl = $this->getFrontController()->getParam("loginFailedUrl");
            
            $auth = Zend_Auth::getInstance();
            if ( $auth->hasIdentity() ) {
                // Identity exists; get it
                $this->_user = $auth->getIdentity();
                Zend_Registry::set( 'user', $this->_user );
            }
            
            if ( empty( $this->_user ) ) {
                $this->_redirect( $failedUrl );
            }
            if ( $this->_requiresSecurity ) {
                $action = $this->getRequest()->getActionName();
                $controller = $this->getRequest()->getControllerName();
                $module = $this->getRequest()->getModuleName();
                // TODO: Make it better
                if ( $failedUrl != '/' . $controller . '/' . $action ) {
                	$this->_applicationId = $this->_helper->getHelper('ExtApplicationHandler')->findIdApp( 
                		$this->getRequest()->getModuleName() 
                	); 
                	$this->_user->applicationId = $this->_applicationId;
                	//print_r($this->_user);
                    if ( ! empty( $this->_user ) ) {
                        if ( ! $this->_user->isAllowed( $controller, $action, $this->_applicationId ) ) {
                            throw new Exception( "Permission denied $controller / $action ($this->_applicationId)" );
                        }
                    } else {
                        $this->_redirect( $failedUrl );
                    }
                }
            }
        }
    }


    /**
     * Averigua si el usuario tiene permisos o no para acceder a esta seccion
     *
     * @param $resource es el recurso al cual el usuario va a acceder
     * @param $privilege si el usuario puede o no acceder a este recurso
     * @uses isAllowed metodo de Zend_Acl
     * @return true  o false, dependiendo si tiene o no permisos para acceder
     */
    public function allow( $resource, $privilege )
    {
        return $this->isAllowed( $resource, $privilege );
    }

    public function isAllowed( $resource, $privilege )
    {
        if ( empty( $this->_user ) ) {
            return false;
        }
        return $this->_user->isAllowed( $resource, $privilege );
    }
}